import website from '@/config/website';
// import  API_CONFIG from "../../vue.config.js"

export const websocket = {
    data() {
        return {
            lockReconnect: false,
            wsUrl: website.websocketUrl,
            ws: '',
            timeout: 30000,
            timeoutObj: null,
            serverTimeoutObj: null
        }
    },
    created() {
        this.createWebSocket()
    },
    destroyed() {
        this.ws.close() //离开路由之后断开websocket连接
    },
    methods: {
        heartCheckstart() {
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(() => {
                //发送测试信息，后端收到后，返回一个消息，
                this.ws.send("ping");
                this.serverTimeoutObj = setTimeout(() => {
                    this.ws.close();
                }, this.timeout);
            }, this.timeout)
        },
        createWebSocket() {
            try {
                this.ws = new WebSocket(this.wsUrl);
                this.websocketInit();
                // if (this.ws == '') {
                //     this.ws = new WebSocket(this.wsUrl);
                //     this.websocketInit();
                // } else {
                //     this.ws.close();
                // }
            } catch (e) {
                console.log('catch');
                this.websocketReconnect(this.wsUrl);
            }
        },
        websocketInit() {
            // 建立 web socket 连接成功触发事件
            this.ws.onopen = (evt) => {
                console.log("建立链接");
                let sendData = { test: 'test' };        // 正常的请求数据
                sendData = JSON.stringify(sendData);
                this.ws.send(sendData);
            };
            // 断开 web socket 连接成功触发事件
            this.ws.onclose = (evt) => {
                this.websocketReconnect(this.wsUrl);
                console.log("连接已关闭...");
            };
            // 接收服务端数据时触发事件
            this.ws.onmessage = (evt) => {
                this.onMessage(evt);
            };
            // 通信发生错误时触发
            this.ws.onerror = (evt) => {
                this.websocketReconnect(this.wsUrl);
                console.log('通信错误：' + evt.data);
            };
        },
        onMessage(evt) {
            console.log('接收消息: ' + evt.data);
            if ("新增一条告警信息" == evt.data) {
                this.$router.go(0);
            }

            //拿到任何消息都说明当前连接是正常的
            this.heartCheckstart();
        },
        websocketReconnect(url) {
            if (this.lockReconnect) {       // 是否已经执行重连
                return;
            }
            this.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            let tt = ''
            tt && clearTimeout(tt);
            tt = setTimeout(() => {
                this.createWebSocket(url);
                this.lockReconnect = false;
            }, 5000);
        },


    }
}